package com.chen.boot.db.handler;

import com.chen.common.Dates;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

import lombok.SneakyThrows;

/**
 * Mybatis数组,符串互转
 * <p>
 * MappedJdbcTypes 数据库中的数据类型 MappedTypes java中的的数据类型
 *
 * @author xuzihui
 * @date 2019-11-20
 */
@MappedTypes(value = {LocalDateTime.class})
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, Dates.asString(parameter,"yyyy-MM-dd HH:mm:ss"));
	}

	@Override
	@SneakyThrows
	public LocalDateTime getNullableResult(ResultSet rs, String columnName) {
		String reString = rs.getString(columnName);
		return Dates.asLocalDateTime(reString);
	}

	@Override
	@SneakyThrows
	public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) {
		String reString = rs.getString(columnIndex);
		return Dates.asLocalDateTime(reString);
	}

	@Override
	@SneakyThrows
	public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) {
		String reString = cs.getString(columnIndex);
		return Dates.asLocalDateTime(reString);
	}
}
